import React from "react";
import {
  Form,
  Input,
  Button,
  DatePicker,
  TimePicker,
  message,
  Tag,
  Select,
} from "antd";
// import { DatePicker, List } from "antd-mobile";
import axios from "axios";
import qs from "qs";
import moment from "moment";
import WCascader from "./WCascader";
import WOrglist from "./WOrglist";
import "../mock/orgtree.js";
import "../mock/org3145.js";

const { Option } = Select;

export default class WEditTable extends React.Component {
  constructor(props) {
    super(props);
    this.changeJoin = this.changeJoin.bind(this);
    this.state = {
      hostMockData: [], //职工列表
      joinMockData: [], //职工列表
      hostTargetKeys: [],
      joinTargetKeys: [],
      rules: [
        {
          required: true,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      loading: false,
      menus: [],

      //不传值时字段为空
      meetingData: props.meetingData
        ? props.meetingData
        : {
            host: "",
            key: "",
            meetingAddress: "",
            meetingDate: "",
            meetingRoom: "",
            meetingTime: "",
            participator: [],
            remindTime: "",
            title: "",
            type: "",
          },
    };
  }

  async getNewTree(orgId) {
    let orgUrl = "orgTree.rst?id=" + orgId;
    let res = await axios.get(orgUrl);
    let response = res.data;
    console.log(res);
    // let response = res;
    if (response.resultCode === 0) {
      let data = response.result.data;
      this.setState({
        menus: data.map((data, index) => {
          return {
            id: data.id,
            text: data.text,
            isLeaf: data.children.length === 0,
            children: data.children,
          };
        }),
      });
    } else {
      message.error("数据请求失败");
    }
  }

  changeJoin = (value) => {
    /**修改参会人 */
    console.log(value);
    this.setState({
      joinTargetKeys: value,
    });
  };

  onFinish = (values) => {
    console.log(values);
    // 进入提交
    this.setState({ loading: true });
    /**提醒时间 */
    let meetingDate = undefined;
    let remindTime = undefined;
    let meetingDateVal = undefined;
    let meetingTime = undefined;
    let id = undefined;

    if (values.date) {
      meetingDate = values.date ? values.date._d.getTime() : undefined;
      remindTime = new Date(meetingDate - values.remindTime * 60 * 1000).Format(
        "yyyy-MM-dd HH:mm:ss"
      );
      meetingDateVal = values.date.format("YYYY-MM-DD");
      meetingTime = values.date.format("HH:mm");
    }
    if (this.props.meetingData) {
      /**修改会议 */
      id = this.state.meetingData.key;
      axios({
        url: "updatemeeting.rst",
        method: "post",
        data: qs.stringify({
          id: id,
          meetingTypePerson: 0,
          meetingDate: meetingDateVal,
          meetingTime: meetingTime,
          locale: values.address,
          theme: values.content,
          host: this.state.hostTargetKeys.join(),
          participator: this.state.joinTargetKeys.join(),
          meetingRoom: values.meetingRoom,
          remindTime: remindTime,
          enable: 1,
        }),
      })
        .then((res) => {
          let response = res.data;
          if (response.resultCode === 0) {
            /**清空并关闭添加表单 */
            message.success("提交成功");
            this.setState({ loading: false, addVisible: false });
            /**重新渲染会议列表 */
            this.props.getDataSource();
          } else {
            message.error("提交失败");
          }
        })
        .catch((error) => {
          message.error("提交失败");
          this.setState({ loading: false, addVisible: false });
        });
    } else {
      /**添加会议 */

      axios
        .post(
          "addWeekMeetingPersonal.rst",
          qs.stringify({
            meetingTypePerson: values.meetingTypePerson,
            meetingDate: meetingDateVal,
            meetingTime: meetingTime,
            host: this.state.hostTargetKeys.join(),
            participator: this.state.joinTargetKeys.join(),
            locale: values.address,
            theme: values.content,
            meetingRoom: values.meetingRoom,
            remindTime: remindTime,
            enable: 1,
          })
        )
        .then((res) => {
          console.log(res);
          let response = res.data;
          if (response.resultCode === 0) {
            /**清空并关闭添加表单 */
            this.formRef.current.resetFields();
            this.setState({
              loading: false,
              addVisible: false,
            });
            /**重新渲染会议列表 */
            this.props.getWeek();
            message.success("提交成功");
          } else {
            this.setState({ loading: false, addVisible: false });
            message.error("提交失败");
          }
        })
        .catch((error) => {
          this.setState({ loading: false, addVisible: false });
          message.error("提交失败");
        });
    }
  };
  componentDidMount() {
    this.getNewTree("");
    console.log(this.state.meetingData);
    this.setState({
      joinTargetKeys: this.state.meetingData.participator,
      hostTargetKeys: [this.state.meetingData.host],
    });
  }
  joinForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleJoinTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };
  /**关闭Tag */
  handleHostTagClose = (removedTag) => {
    const hostTargetKeys = this.state.hostTargetKeys.filter(
      (hostTargetKeys) => hostTargetKeys !== removedTag
    );
    console.log(hostTargetKeys);
    this.setState({ hostTargetKeys });
  };
  handleJoinTagClose = (removedTag) => {
    const joinTargetKeys = this.state.joinTargetKeys.filter(
      (joinTargetKeys) => joinTargetKeys !== removedTag
    );
    console.log(joinTargetKeys);
    this.setState({ joinTargetKeys });
  };

  render() {
    const { loading, menus, meetingData, joinTargetKeys } = this.state;
    const joinTag = joinTargetKeys.map(this.joinForMap);

    let meetingTypePerson = (
      <Select style={{ width: 180 }} defaultValue="0" allowClear>
        <Option value="0">会议</Option>
      </Select>
    );
    if (!this.props.onlyMeeting) {
      meetingTypePerson = (
        <Select style={{ width: 180 }} allowClear>
          <Option value="0">会议</Option>
          <Option value="1">活动</Option>
        </Select>
      );
    }

    return (
      <div>
        <Form
          name="add-meeting"
          onFinish={this.onFinish} /**表单提交事件 */
          ref={this.formRef}
          className="Wedit-form search-meet"
        >
          <Form.Item name="meetingTypePerson" label="类型">
            {meetingTypePerson}
          </Form.Item>
          <Form.Item name="date" label="会议日期">
            <DatePicker
              format="YYYY-MM-DD"
              defaultValue={
                meetingData.meetingDate
                  ? moment(meetingData.meetingDate, "YYYY/MM/DD")
                  : ""
              }
            />
          </Form.Item>
          <Form.Item name="date" label="会议时间">
            <TimePicker
              format="HH:mm"
              defaultOpenValue={moment("12:30", "HH:mm")}
              defaultValue={
                meetingData.meetingTime
                  ? moment(meetingData.meetingTime, "HH:mm")
                  : ""
              }
            />
          </Form.Item>
          <Form.Item name="remindTime" label="提醒时间">
            <Select
              style={{ width: 180 }}
              allowClear
              defaultValue={meetingData.remindTime.substr(11)}
            >
              <Option value="10">提前10分钟</Option>
              <Option value="15">提前15分钟</Option>
              <Option value="30">提前30分钟</Option>
              <Option value="60">提前60分钟</Option>
            </Select>
          </Form.Item>
          <Form.Item name="address" label="地点">
            <Input defaultValue={meetingData.meetingAddress} />
          </Form.Item>
          <Form.Item name="meetingRoom" label="会议室">
            <Input defaultValue={meetingData.meetingRoom} />
          </Form.Item>
          <Form.Item name="content" label="内容">
            <Input defaultValue={meetingData.title} />
          </Form.Item>
          {/* <Form.Item name="host" label="主持人">
            <WCascader menus={menus} />
          </Form.Item> */}
          <Form.Item name="join" label="参加人">
            {joinTag}
            {/* <WCascader
              menus={menus}
              changeJoin={this.changeJoin}
              users={joinTargetKeys}
            /> */}
            <WOrglist
              menus={menus}
              changeJoin={this.changeJoin}
              users={joinTargetKeys}
            />
          </Form.Item>

          <Button type="primary" htmlType="submit" loading={loading}>
            保存
          </Button>
        </Form>
      </div>
    );
  }
}
